#include <string.h>
#include "mqtt.h"
#include "z_logger.h"

int mqtt_write(mqtt_handler_t *handler, const char *topic, void *payload, int len) {
    int rc = 0;

    if (0 == strcmp(handler->topic, topic)) {
        if ((handler->ps + len) > handler->pe) {
            rc = mqtt_flush(handler, topic);
        }
    } else {
        mqtt_flush(handler, handler->topic);
        memcpy(handler->topic, topic, sizeof(handler->topic));
    }

    memcpy(handler->ps, payload, len);
    handler->ps += len;

    return rc;
}

int mqtt_flush(mqtt_handler_t *handler, const char *topic) {
    if (NULL == topic) {
        topic = handler->topic;
    }

    int len = handler->ps - handler->payload;
    handler->ps = handler->payload;

    if (len > 0) {
        log_debug("topic=%s, payload_len=%d", topic, len);
        return mosquitto_publish(handler->mosq, NULL, topic, len, handler->payload, 1/*QoS*/, false);
    } else {
        return MOSQ_ERR_SUCCESS;
    }
}

